<!-- 区域树形下拉列表 -->
<template>
  <a-tree-select class="region-select-wp"
    v-model:value="regionValue"
    placeholder="请选择"
    allow-clear
    :tree-data="treeData"
    :treeDefaultExpandedKeys="['540000', '540300']"
    :fieldNames="{label: 'label', value: 'value', children: 'children'}">
  </a-tree-select>
</template>

<script setup>
	import { reactive, ref, onMounted, computed } from 'vue'

	import {httpPost} from "@/api";
	import {list} from "@/api/regions.ts";

	const emit = defineEmits(['update:modelValue'])

	const props = defineProps({
		// 值， - 空值: ''
		modelValue: {
			type: String
		},
		// 数据登记，3位到镇，2到县
		lv: {
			type: [String,Number],
			default: '3',
			validator: value => {
				return value >= 0 && value <= 3;
			}
		}
	})

	// 数据列表
	const treeData = ref([]);

	// 区域值
	const regionValue = computed({
		get: () => {
			return props.modelValue || undefined;
		},
		set: (value) => {
			emit('update:modelValue', value);
		}
	})

  onMounted(() => {
		getData();
	})

	function getData() {
		// treeData.value = [
		// 	{title: '昌都市', value: '500', children: [
		// 		{title: '卡若区', value: '500001', children: [
		// 			{title: '城关镇', value: '500001001'},
		// 			{title: '卡若镇', value: '500001002'},
		// 			{title: '埃西乡', value: '500001003'},
		// 		]},
		// 		{title: '察雅县', value: '500002'},
		// 		{title: '八宿县', value: '500003'},
		// 		{title: '左贡县', value: '500004'},
		// 	]}
		// ];

		list(props.lv).then(res => {
			if(!res || res.code) {
				return;
			}
			treeData.value = recursion(res);
		})
	}

	// 递归
	function recursion(list) {
		let arr = [];
		for (let i = 0 ; i < list.length; i++) {
			let item = list[i];
			let obj = {
				label: item.areaName,
				value: item.id
			}
			if(item.children) {
				obj.children = recursion(item.children);
			}
			arr.push(obj);
		}
		return arr;
	}


	defineExpose({
		reload: getData
	});

</script>
<style lan="less" scoped>
.region-select-wp {
	min-width: 230px;
}
</style>